<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="clearfix">
            <span>设备控制</span>
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              @click="refreshDeviceList">
              刷新设备列表
            </el-button>
          </div>

          <el-form :model="controlForm" label-width="100px">
            <el-form-item label="选择设备">
              <el-select
                v-model="controlForm.deviceId"
                filterable
                placeholder="请选择设备"
                style="width: 100%">
                <el-option
                  v-for="device in deviceList"
                  :key="device.deviceId"
                  :label="`${device.deviceId} (${device.status ? '在线' : '离线'})`"
                  :value="device.deviceId"
                  :disabled="!device.status">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="控制命令">
              <el-input
                v-model="controlForm.command"
                type="textarea"
                :rows="5"
                placeholder="请输入控制命令">
              </el-input>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                @click="sendCommand"
                :disabled="!controlForm.deviceId || !controlForm.command">
                发送命令
              </el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="clearfix">
            <span>批量设备控制</span>
          </div>

          <el-form :model="batchControlForm" label-width="100px">
            <el-form-item label="选择设备">
              <el-transfer
                v-model="selectedDevices"
                :data="deviceOptions"
                :titles="['可选设备', '已选设备']"
                filterable
                filter-placeholder="搜索设备">
              </el-transfer>
            </el-form-item>

            <el-form-item label="控制命令">
              <el-input
                v-model="batchControlForm.command"
                type="textarea"
                :rows="4"
                placeholder="请输入控制命令">
              </el-input>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                @click="handleBatchControl"
                :disabled="selectedDevices.length === 0 || !batchControlForm.command">
                发送批量命令
              </el-button>
              <el-button @click="handleSelectByStatus(true)">选择所有在线设备</el-button>
              <el-button @click="handleSelectByStatus(false)">选择所有离线设备</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="clearfix">
            <span>控制历史</span>
          </div>

          <el-table :data="controlHistory" style="width: 100%">
            <el-table-column prop="deviceId" label="设备ID" min-width="150"></el-table-column>
            <el-table-column prop="command" label="命令" min-width="200"></el-table-column>
            <el-table-column prop="timestamp" label="发送时间" width="180">
              <template slot-scope="scope">
                {{ formatTime(scope.row.timestamp) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  getDeviceStatusList,
  sendDeviceCommand,
  batchSendDeviceCommand,
  getControlHistory
} from '@/api/smart/device'

export default {
  name: 'DeviceControl',
  data() {
    return {
      deviceList: [],
      deviceOptions: [],
      selectedDevices: [],
      controlForm: {
        deviceId: '',
        command: ''
      },
      batchControlForm: {
        command: ''
      },
      controlHistory: []
    }
  },
  created() {
    this.getDeviceList()
    this.getControlHistoryList()
  },
  computed: {
    formattedDevices() {
      return this.deviceList.map(device => ({
        key: device.deviceId,
        label: `${device.deviceId} (${device.status ? '在线' : '离线'})`,
        disabled: !device.status
      }))
    }
  },
  watch: {
    deviceList: {
      immediate: true,
      handler(newVal) {
        this.deviceOptions = newVal.map(device => ({
          key: device.deviceId,
          label: `${device.deviceId} (${device.status ? '在线' : '离线'})`,
          disabled: !device.status
        }))
      }
    }
  },
  methods: {
    getDeviceList() {
      getDeviceStatusList().then(response => {
        this.deviceList = Object.keys(response.data).map(deviceId => ({
          deviceId,
          status: response.data[deviceId]
        }))
      })
    },

    getControlHistoryList() {
      // 这里可以获取所有设备的控制历史，或者选择特定设备的历史
      // 简化实现，只获取最近10条历史记录
      getControlHistory('all', 10).then(response => {
        this.controlHistory = response.data
      })
    },

    refreshDeviceList() {
      this.getDeviceList()
      this.$message.success('设备列表已刷新')
    },

    sendCommand() {
      if (!this.controlForm.deviceId) {
        this.$message.warning('请选择设备')
        return
      }

      if (!this.controlForm.command) {
        this.$message.warning('请输入控制命令')
        return
      }

      sendDeviceCommand(this.controlForm.deviceId, this.controlForm.command).then(() => {
        this.$message.success('命令已发送')
        this.resetForm()
        this.getControlHistoryList()
      })
    },

    resetForm() {
      this.controlForm = {
        deviceId: '',
        command: ''
      }
    },

    handleBatchControl() {
      if (this.selectedDevices.length === 0) {
        this.$message.warning('请选择要控制的设备')
        return
      }

      if (!this.batchControlForm.command) {
        this.$message.warning('请输入控制命令')
        return
      }

      const deviceCommands = {}
      this.selectedDevices.forEach(deviceId => {
        deviceCommands[deviceId] = this.batchControlForm.command
      })

      batchSendDeviceCommand(deviceCommands).then(() => {
        this.$message.success('批量命令已发送')
        this.batchControlForm.command = ''
        this.selectedDevices = []
        this.getControlHistoryList()
      })
    },

    handleSelectByStatus(online) {
      this.selectedDevices = this.deviceList
        .filter(device => device.status === online)
        .map(device => device.deviceId)

      this.$message.success(`已选择所有${online ? '在线' : '离线'}设备`)
    },

    formatTime(timestamp) {
      if (!timestamp) return '未知'
      return this.$moment(timestamp).format('YYYY-MM-DD HH:mm:ss')
    }
  }
}
</script>
